//
//  LoginViewController.m
//  JiuJiuShangCheng
//
//  Created by jiujiukeji on 2018/7/16.
//  Copyright © 2018年 jiujiukeji. All rights reserved.
//

#import "LoginViewController.h"
#import "LoginItem.h"
#import "RegistViewController.h"
#import "FindPasswordViewController.h"
#import "RootTabBarViewController.h"
#import "MD5Encrypt.h"
#import <ShareSDK/ShareSDK.h>
// 引入 JPush 功能所需头文件
#import "JPUSHService.h"

@interface LoginViewController ()

@property (nonatomic, strong) LoginItem *phoneItem;
@property (nonatomic, strong) LoginItem *passwordItem;
@property (nonatomic, assign) NSInteger loginType;

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    
    NSLog(@"-----%@",[GetTimestamp getNowTimeTimestamp]);
    
    [self setUpUI];
    [self loadBaseTitleLable:@""];
    self.navTitleBgView.backgroundColor = kClearColor;
    [self.leftBtn addTarget:self action:@selector(backAction) forControlEvents:(UIControlEventTouchUpInside)];
}
- (void)backAction
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)setUpUI
{
    WeakSelf
    UIImageView *bgImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    bgImg.image = UIImageNamed(@"loginbgimg");
    [self.view addSubview:bgImg];
    bgImg.userInteractionEnabled = YES;
    
    UIImageView *headBgImg = [[UIImageView alloc] init];
    headBgImg.image = UIImageNamed(@"headquan");
    [headBgImg sizeToFit];
    [bgImg addSubview:headBgImg];
    [headBgImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgImg).offset(SafeAreaTopHeight);
        make.centerX.equalTo(bgImg);
    }];
    headBgImg.userInteractionEnabled = YES;
    
    UIImageView *headImg = [[UIImageView alloc] init];
    headImg.image = UIImageNamed(@"headImgdefault");
    headImg.layer.cornerRadius = rateHeight(110);
    [bgImg addSubview:headImg];
    [headImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(headBgImg);
        make.size.mas_offset(CGSizeMake(rateHeight(220), rateHeight(220)));
    }];
    headImg.userInteractionEnabled = YES;
    
    self.phoneItem = [[LoginItem alloc] init];
    _phoneItem.icon.image = UIImageNamed(@"shoujilogin");
    _phoneItem.textField.placeholder = @"请输入手机号...";
    [bgImg addSubview:_phoneItem];
    [_phoneItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgImg);
        make.top.equalTo(headBgImg.mas_bottom).offset(rateHeight(80));
        make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
    }];
    
    self.passwordItem = [[LoginItem alloc] init];
    _passwordItem.icon.image = UIImageNamed(@"suologin");
    _passwordItem.textField.placeholder = @"请输入密码...";
    _passwordItem.textField.secureTextEntry = YES;
    [bgImg addSubview:_passwordItem];
    [_passwordItem mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bgImg);
        make.top.equalTo(weakSelf.phoneItem.mas_bottom);
        make.size.mas_offset(CGSizeMake(kScreenWidth, rateHeight(90)));
    }];
    
    // 注册
    UIButton *registBtn = [UIButton buttonWithTitle:@"注册" fontSize:13 titleColor:UIColorWhite background:kClearColor cornerRadius:3];
    registBtn.layer.borderColor = UIColorWhite.CGColor;
    registBtn.layer.borderWidth = 1;
    [bgImg addSubview:registBtn];
    [registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.passwordItem.line);
        make.top.equalTo(weakSelf.passwordItem.mas_bottom).offset(rateHeight(50));
        make.size.mas_offset(CGSizeMake(rateWidth(140), rateHeight(60)));
    }];
    [registBtn addActionHandler:^{
        RegistViewController *registVC = [[RegistViewController alloc] init];
        [weakSelf presentViewController:registVC animated:YES completion:nil];
    }];
    
    // 忘记密码
    UIButton *forgetPWBtn = [UIButton buttonWithTitle:@"忘记密码" fontSize:13 titleColor:UIColorWhite background:kClearColor cornerRadius:3];
    forgetPWBtn.layer.borderColor = UIColorWhite.CGColor;
    forgetPWBtn.layer.borderWidth = 1;
    [bgImg addSubview:forgetPWBtn];
    [forgetPWBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.passwordItem.line);
        make.centerY.equalTo(registBtn);
        make.size.mas_offset(CGSizeMake(rateWidth(140), rateHeight(60)));
    }];
    [forgetPWBtn addActionHandler:^{
        FindPasswordViewController *findVC = [[FindPasswordViewController alloc] init];
        [weakSelf presentViewController:findVC animated:YES completion:nil];
    }];
    
    // 登录
    UIButton *loginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [loginBtn setImage:UIImageNamed(@"loginbtnimg") forState:(UIControlStateNormal)];
    loginBtn.showsTouchWhenHighlighted = NO;
    loginBtn.adjustsImageWhenHighlighted = NO;
    [loginBtn sizeToFit];
    [bgImg addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgImg);
        make.top.equalTo(registBtn.mas_bottom).offset(rateHeight(55));
    }];
    // 登录
    [loginBtn addTarget:self action:@selector(loginAction) forControlEvents:(UIControlEventTouchUpInside)];
    
    // 三方登录
    UILabel *label = [UILabel labelWithText:@"第三方登录" textColor:UIColorWhite fontSize:13];
    [label sizeToFit];
    [bgImg addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgImg);
        make.top.equalTo(loginBtn.mas_bottom).offset(rateHeight(70));
    }];
    
    UIView *line1 = [[UIView alloc] init];
    line1.backgroundColor = [UIColorWhite colorWithAlphaComponent:0.5];
    [bgImg addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(label.mas_left).offset(-rateWidth(50));
        make.size.mas_offset(CGSizeMake(rateWidth(210), rateHeight(2)));
        make.centerY.equalTo(label);
    }];
    UIView *line2 = [[UIView alloc] init];
    line2.backgroundColor = [UIColorWhite colorWithAlphaComponent:0.5];
    [bgImg addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(label.mas_right).offset(rateWidth(50));
        make.size.mas_offset(CGSizeMake(rateWidth(210), rateHeight(2)));
        make.centerY.equalTo(label);
    }];
    
    UIButton *loginBtn1 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [loginBtn1 setImage:UIImageNamed(@"QQ") forState:(UIControlStateNormal)];
    [bgImg addSubview:loginBtn1];
    [loginBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(bgImg);
        make.top.equalTo(label.mas_bottom).offset(rateHeight(45));
    }];
    loginBtn1.tag = 2;
    
    UIButton *loginBtn2 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [loginBtn2 setImage:UIImageNamed(@"weixin") forState:(UIControlStateNormal)];
    [bgImg addSubview:loginBtn2];
    [loginBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(loginBtn1.mas_left).offset(-rateWidth(60));
        make.centerY.equalTo(loginBtn1);
    }];
    loginBtn2.tag = 1;
    
    UIButton *loginBtn3 = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [loginBtn3 setImage:UIImageNamed(@"weibo") forState:(UIControlStateNormal)];
    [bgImg addSubview:loginBtn3];
    [loginBtn3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(loginBtn1.mas_right).offset(rateWidth(60));
        make.centerY.equalTo(loginBtn1);
    }];
    loginBtn3.tag = 3;
    [loginBtn1 addTarget:self action:@selector(ThirdParty:) forControlEvents:(UIControlEventTouchUpInside)];
    [loginBtn2 addTarget:self action:@selector(ThirdParty:) forControlEvents:(UIControlEventTouchUpInside)];
    [loginBtn3 addTarget:self action:@selector(ThirdParty:) forControlEvents:(UIControlEventTouchUpInside)];
}
#pragma mark - 三方登录
- (void)ThirdParty:(UIButton *)btn
{
    switch (btn.tag) {
        case 1:
        {
            // 微信
            [self loginWithUUU:997];
            self.loginType = 1;
        }
            break;
        case 2:
        {
            // QQ
            [self loginWithUUU:998];
            self.loginType = 2;
        }
            break;
        case 3:
        {
            // 微博
            [self loginWithUUU:1];
            self.loginType = 3;
        }
            break;
        default:
            break;
    }
}
- (void)loginWithUUU:(NSInteger)type
{
    //    [ShareSDK cancelAuthorize:type]; // 退出微信/微博/qq登录
    // 微信/微博/qq登录
    [ShareSDK getUserInfo:type
           onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
     {
         if (state == SSDKResponseStateSuccess)
         {
             NSLog(@"uid=%@",user.uid);
             NSLog(@"%@",user.credential);
             NSLog(@"token=%@",user.credential.token);
             NSLog(@"nickname=%@",user.nickname);
             NSLog(@"nickname=%@",user.icon);
             
             NSLog(@"unionid=%@",user.rawData[@"unionid"]);
             
             NSString *loginType;
             if (self.loginType == 1) {
                 loginType = @"wxlogin";
             } else if (self.loginType == 2) {
                 loginType = @"qqlogin";
             } else if (self.loginType == 3) {
                 loginType = @"sinalogin";
             }
             // 判断是否开启限制广告追踪
             NSString *appkey;
             if ([[ASIdentifierManager sharedManager] isAdvertisingTrackingEnabled]) {
                 // 返回YES说明没有 “开启限制广告跟踪”,如果返回的是NO，说明等待你的就是一串00000000000
                 //        NSLog(@"idfa-----%@",[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]);
                 appkey = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
             } else {
                 //        NSLog(@"SimulateIDFA-----%@",[SimulateIDFA createSimulateIDFA]);
                 appkey = [SimulateIDFA createSimulateIDFA];
             }
             NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
             [MBProgressHUD showMessage:nil toView:self.view];
             [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=otherlogin&companyid=%@&code=%@&timestamp=%@&type=%@&openid=%@&unionid=%@&nickname=%@&sex=%ld&headimgurl=%@&appos=%@&appkey=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],loginType,user.uid,user.rawData[@"unionid"],user.nickname,(long)user.gender,user.icon,@"IOS",appkey] parameters:nil success:^(id responseObject) {
                 [MBProgressHUD hideHUDForView:self.view];
                 
                 if ([responseObject[@"status"] intValue] == 1) {
                     NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
                     NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:cookies];
                     [UserDefaults setObject:cookiesData forKey:@"cookie"];
                     
                     [UserDefaults setObject:@"1" forKey:@"isLogin"];
                     [UserDefaults setObject:user.uid forKey:@"uid"];
                     //                     [UserDefaults setObject:self.phoneItem.textField.text forKey:@"userName"];
                     //                     [UserDefaults setObject:self.passwordItem.textField.text forKey:@"password"];
                     [UserDefaults setObject:loginType forKey:@"LoginTypeStr"];
                     // 登录成功跳转主页面
//                     RootTabBarViewController *mainVC = [[RootTabBarViewController alloc] init];
//                     [UIApplication sharedApplication].keyWindow.rootViewController = mainVC;
                     [self dismissViewControllerAnimated:YES completion:nil];
                     
                     [JPUSHService setTags:[NSSet setWithObject:@"member"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
                         
                     } seq:0];
                 } else {
                     [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
                 }
                 
             } failure:^(NSError *error) {
                 [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
                 
             }];
         }
         else
         {
             NSLog(@"============登录状态：%lu",(unsigned long)state);
             [TFHUD addRemindHUD:self.view message:@"登录失败"];
             NSLog(@"%@",error);
         }
     }];
}
#pragma mark - 登录按钮
- (void)loginAction
{
    NSString *code = [NSString stringWithFormat:@"%@%@",safeCode,[GetTimestamp getNowTimeTimestamp]];
    if (_phoneItem.textField.text.length != 0 && _passwordItem.textField.text.length != 0) {
        [MBProgressHUD showMessage:nil toView:self.view];
        [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/member/member.ashx?action=login&companyid=%@&code=%@&timestamp=%@&name=%@&pwd=%@",kServerURL,companyId,[MD5Encrypt  MD5ForLower32Bate:code],[GetTimestamp getNowTimeTimestamp],_phoneItem.textField.text,_passwordItem.textField.text] parameters:nil success:^(id responseObject) {
            [MBProgressHUD hideHUDForView:self.view];
            
            if ([responseObject[@"status"] intValue] == 1) {
                NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
                NSData *cookiesData = [NSKeyedArchiver archivedDataWithRootObject:cookies];
                [UserDefaults setObject:cookiesData forKey:@"cookie"];
                [UserDefaults setObject:@"1" forKey:@"isLogin"];
                [UserDefaults setObject:self.phoneItem.textField.text forKey:@"userName"];
                [UserDefaults setObject:self.passwordItem.textField.text forKey:@"password"];
                // 登录成功跳转主页面
//                RootTabBarViewController *mainVC = [[RootTabBarViewController alloc] init];
//                [UIApplication sharedApplication].keyWindow.rootViewController = mainVC;
                [self dismissViewControllerAnimated:YES completion:nil];
                
                [JPUSHService setTags:[NSSet setWithObject:@"member"] completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
                    
                } seq:0];
            } else {
                [TFHUD addRemindHUD:self.view message:responseObject[@"returnMsg"]];
            }
            
        } failure:^(NSError *error) {
            [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
            
        }];
        
    } else {
        [TFHUD addRemindHUD:self.view message:@"请输入用户名和密码"];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
